package teach.aistar.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import teach.aistar.model.entity.User;
import teach.aistar.model.vo.Result;
import teach.aistar.service.IUserService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class Register1Controller {


    @Autowired
    IUserService userService;
    @PostMapping("/register1")
    @ResponseBody
    public Result register(@Validated User user, BindingResult bindingResult){

        List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
        Map<String,String> errorsMap = new HashMap<>();

        if(null!=fieldErrorList && fieldErrorList.size()>0){
            for (FieldError f : fieldErrorList) {
                System.out.print(f.getField()+"=>");
                System.out.println(f.getDefaultMessage());
                errorsMap.put(f.getField(),f.getDefaultMessage());
            }
            return new Result("500","注册失败",errorsMap);
        }
            else
            {
                System.out.println(user);

                User user1 = userService.getByUsername(user.getUname());

                if(user1==null) {
                    userService.add(user);
                    return new Result("200", "注册成功", null);
                }
                else
                {
                    return new Result("401", "用户名已经存在，请重新注册", null);
                }
            }
        }
    }
